package org.jeecg.common.core;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.common.util.auto_wrapper.AutoWhereUtil;
import org.jeecg.common.util.mputil.MpUtil2;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.function.BiConsumer;

/**
 * 基本控制器
 *
 * @author addzero
 * @since 2022/10/04
 */
//@SuppressWarnings("all")
@RestController
public abstract class BasePairController<S extends IService<PO>
        , CS extends IService<CO>
        , PO, CO> {

    @Autowired
    protected S service;

    @Autowired
    protected CS cs;
    protected MpUtil2<PO, CO> mpUtil2;
    private SFunction<PO, String> pGetPidFun;
    private SFunction<CO, String> cGetPidFun;

    private BiConsumer<CO, String> cSetPidCon;
    private SFunction<PO, List<CO>> getCosFun;

    private BiConsumer<CO, PO> cSetProFromFun;

    public void setFun(SFunction<PO, String> pGetPidFunm, SFunction<CO,String> cGetPidFun,BiConsumer<CO, String> cSetPidCon, SFunction<PO, List<CO>> getCosFun, BiConsumer<CO, PO> cSetProFromFun) {
        this.pGetPidFun = pGetPidFunm;
        this.cGetPidFun = cGetPidFun;
        this.cSetPidCon = cSetPidCon;
        this.getCosFun = getCosFun;
        this.cSetProFromFun = cSetProFromFun;
    }
    @PostConstruct
    public void init() {
        MpUtil2<PO, CO> of = MpUtil2.of(service, cs);
        this.mpUtil2 = of;
    }

    @ApiOperation("分页列表查询")
    @GetMapping(value = "/list")
    public Page<PO> list(PO po, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<PO> lambdaQueryWrapper = (QueryWrapper<PO>) AutoWhereUtil.queryByField(po.getClass(), po);
        Page<PO> page = new Page<>(pageNo, pageSize);
        Page<PO> page2 = service.page(page, lambdaQueryWrapper);
        return page2;
    }


    @PostMapping("/add")
    @ApiOperation("添加")
    public Result<Boolean> add(@RequestBody PO po) {
        List<CO> apply = getCosFun.apply(po);
        mpUtil2.pSave(po, apply, pGetPidFun, cSetPidCon);
        return Result.OK("添加成功!");
    }

    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @ApiOperation("编辑")
    public Result<Boolean> edit(@RequestBody PO po ) {
        List<CO> apply = getCosFun.apply(po);
        mpUtil2.pUpdate(po, apply, pGetPidFun, cGetPidFun, cSetProFromFun);
        return Result.OK("修改成功", true);
    }

}
